﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BusinessLogic.Messages;
using System.Threading.Tasks;
using OpenPop.Mime;
using Common.Utils;
using BusinessLogic.Configuration;
using System.Diagnostics;

namespace MailWindowsService 
{
    public class MainService : BaseAdministration
    {        
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            try {
                this.Receive();
            }
            catch (Exception ex)
            {
                this.WriteToEventLog(ex.Message);
            }
        }
        #region Function
        private void Receive()
        {
            int i = 0;
            string path = "";
            string FileName = "";
            List<string> seenUids = new List<string>();
            List<Result> List = new List<Result>();
            string fileAttachment = "";
            
            EmailAccount account = this.MessageService.DefaultEmailAccount;
            List<Message> newMessages = this.MessageService.FetchUnseenMessages(account.Host, account.Port, account.EnableSSL, account.Username, account.Password, seenUids);
            foreach (var messages in newMessages)
            {
                List<MessagePart> attachments = messages.FindAllAttachments();
                MessagePart plainText = messages.FindFirstPlainTextVersion();
                List = new List<Result>();
                
                foreach (MessagePart attachment in attachments)
                {
                    string key = seenUids[i];
                    path = string.Format(@"{0}\{1}\{2}\{3}\{4}", PayrollConfig.appPath, "attachment", messages.Headers.From.MailAddress.Address, DateTime.Now.ToString("yyyy-MM-dd"), seenUids[i]);

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string fileExten = attachment.FileName.EndsWith(".txt", StringComparison.Ordinal) ? ".txt" : (attachment.FileName.EndsWith(".xls", StringComparison.Ordinal) ? ".xls" : (attachment.FileName.EndsWith(".xlsx", StringComparison.Ordinal) ? ".xlsx" : ""));
                    switch (fileExten)
                    {
                        case ".xlsx":
                            FileName = string.Format(@"{0}\\{1}", path, attachment.FileName);
                            File.WriteAllBytes(FileName, attachment.Body);
                            this.Excel(ref List, FileName);      
                            break;
                        case ".txt":
                            FileName = string.Format(@"{0}\\{1}", path, attachment.FileName);
                            File.WriteAllBytes(FileName, attachment.Body);
                            if (fileAttachment.Length > 0)
                                fileAttachment += ";" + FileName;
                            else
                                fileAttachment = FileName;

                            break;
                    }                                                    
                }
                MessageMails message = new MessageMails
                {
                    Body = plainText.GetBodyAsText(),
                    attachment = fileAttachment,
                    ResDateReceive = DateTime.Now.ToString("MM/dd/yyyy"),
                    Frommail = messages.Headers.From.MailAddress.Address,
                    DateSent = messages.Headers.DateSent.ToString("dd/MM/yyyy"),
                    Createby = 1,
                    Modified = 1,
                    Subject = messages.Headers.Subject,
                    CreateDate = DateTime.Now,
                    ModifiedDate = messages.Headers.DateSent,
                    Results = List
                };
                this.SaveToData(message);
                i += 1;
            }
        }
        /// <summary>
        /// Excels the specified list.
        /// </summary>
        /// <param name="List">The list.</param>
        /// <param name="file">The file.</param>
        private void Excel(ref List<Result> List, string file)
        {
            int startRow = 5;
            string datePurchase = DateTime.Now.ToString("dd/MM/yyyy"); 
            DateTime ResDateReceive = DateTime.Now;
            string PackageCode = "";
            string TaxCode = "";
            string fileInfo = Path.GetDirectoryName(file) + "\\tem-" + Path.GetFileName(file);
            var existingFile = new FileInfo(file);

            FileInfo filewrite = existingFile.CopyTo(fileInfo);
            using (var package = new ExcelPackage(filewrite))
            { 
                ExcelWorkbook workBook = package.Workbook;
                if (workBook != null)
                {
                    if (workBook.Worksheets.Count > 0)
                    {
                        ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
                        int lastRow = currentWorksheet.Dimension.End.Row;
                        for (; startRow <= lastRow; startRow++)
                        {
                            PackageCode = CommonHelper.ToString(currentWorksheet.Cells[startRow, 9].Value);
                            TaxCode = CommonHelper.ToString(currentWorksheet.Cells[startRow, 4].Value);
                            if (PackageCode.Length == 0 || TaxCode.Length == 0)
                            {
                                continue;
                            }
                            List.Add(new Result
                            {
                                PackageCode = PackageCode,
                                DatePurchase = datePurchase,
                                CustomerName = CommonHelper.ToString(currentWorksheet.Cells[startRow, 3].Value),
                                TaxCode = CommonHelper.ToString(currentWorksheet.Cells[startRow, 4].Value),
                                Address = CommonHelper.ToString(currentWorksheet.Cells[startRow, 5].Value),
                                Mobile = CommonHelper.ToString(currentWorksheet.Cells[startRow, 6].Value),
                                Email = CommonHelper.ToString(currentWorksheet.Cells[startRow, 7].Value),
                                ServiceFree = CommonHelper.ToString(currentWorksheet.Cells[startRow, 10].Value),
                                CustomerProfile = CommonHelper.ToString(currentWorksheet.Cells[startRow, 11].Value),
                                ResConfirm = 3,
                                ResStatus = 1
                            });
                        }
                    }
                }
            }
            if (File.Exists(fileInfo))
            {
                File.Delete(fileInfo);
            }
        }
        /// <summary>
        /// Saves to data.
        /// </summary>
        /// <param name="message">The message.</param>
        private void SaveToData(MessageMails message)
        {
            this.ResultsService.Save(message);
        }
        #endregion
        #region Log
        private void WriteToEventLog(string message)
        {
            string cs = "LogError";
            EventLog elog = new EventLog();

            if (!EventLog.SourceExists(cs))
            {
                EventLog.CreateEventSource(cs, cs);
            }
            elog.Source = cs;
            elog.EnableRaisingEvents = true;
            elog.WriteEntry(string.Format("Error {0} : {1}", DateTime.Now.ToString(), message));
        }
        #endregion
    }
}
